package org.nabc.core;

import lombok.extern.slf4j.Slf4j;
import org.nabc.configuration.FileConfiguration;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public abstract class AbstractFileOperation extends AbstractStringOperation {
    protected FileConfiguration fileConfiguration;
    private final Map<String, StringBuffer> fileContentMap = new ConcurrentHashMap<>();

    protected boolean generateFile(String fileName) throws IOException {
        File file = new File(fileConfiguration.getFilePath() + fileName);

        if (!file.exists()) {
            file.createNewFile();
        }

        return true;
    }

    protected boolean generateFolder(String folderName) throws IOException {
        File file = new File(fileConfiguration.getFilePath() + folderName);

        // 双重检测单例
        if (!file.exists()) {
            synchronized (this) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
        }

        return true;
    }

    protected StringBuffer inputFromFile(String fileName) {
        if (fileContentMap.get(fileName) != null) {
            return fileContentMap.get(fileName);
        }

        try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
            StringBuffer stringBuffer = new StringBuffer();

            String str;
            while ((str = in.readLine()) != null) {
                stringBuffer.append(str).append("\n");
            }

            fileContentMap.put(fileName, stringBuffer);

            return stringBuffer;
        } catch (Exception e) {
            log.info("文件 {} 读取错误", fileName);
            return null;
        }
    }

    protected boolean outputToFile(String data, String fileName) throws IOException {
        try (BufferedWriter out = new BufferedWriter(new FileWriter(fileConfiguration.getFilePath() + fileName))) {
            out.write(data);
            out.flush();
        }

        return true;
    }

    protected String[] getTemplate(String regex, String text) {
        Set<String> set = new HashSet<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        List<String> list = new ArrayList<>();
        int i = 0;
        while (matcher.find()) {
            String res = matcher.group();
            if (!res.equals("") && !set.contains(res)) {
                set.add(res);
                list.add(res.substring(2, res.length() - 2));
            }
        }

        return list.toArray(new String[]{});
    }

    public void setFileConfiguration(FileConfiguration fileConfiguration) {
        this.fileConfiguration = fileConfiguration;
    }
}
